<template>
  <div class="falling-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">高空抛物管理系统</h1>
	            <p class="sub-title">严管高空抛物线索，细查每一次异常记录，用精准管理织密 “防坠网”，守护楼下每一份安全</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="坠物事件详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="事件信息" direction="vertical" :column="2" border>
        <el-descriptions-item label="事件ID">{{ detailData.incidentId }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ detailData.status }}</el-descriptions-item>
        <el-descriptions-item label="房产ID">{{ detailData.propertyId }}</el-descriptions-item>
        <el-descriptions-item label="居民ID">{{ detailData.residentId }}</el-descriptions-item>
        <el-descriptions-item label="发生时间">{{ formatDateTime(detailData.incidentDate) }}</el-descriptions-item>
        <el-descriptions-item label="处理人">{{ detailData.handler || '未处理' }}</el-descriptions-item>
        <el-descriptions-item label="处理时间" :span="2">
          {{ detailData.handledAt ? formatDateTime(detailData.handledAt) : '未处理' }}
        </el-descriptions-item>
        <el-descriptions-item label="伤害描述" :span="2">
          {{ detailData.injuryDescription || '无' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editVisible"
      title="编辑坠物事件"
      width="50%"
      destroy-on-close
    >
      <el-form 
        :model="editForm" 
        ref="editFormRef" 
        label-width="120px"
        class="demo-editForm"
      >
        <el-form-item label="事件ID" prop="incidentId">
          <el-input v-model="editForm.incidentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" required>
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="未发生" value="未发生"></el-option>
            <el-option label="已发生" value="已发生"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房产ID" prop="propertyId" required>
          <el-input v-model.number="editForm.propertyId" type="number"></el-input>
        </el-form-item>
        <el-form-item label="居民ID" prop="residentId" required>
          <el-input v-model.number="editForm.residentId" type="number"></el-input>
        </el-form-item>
        <el-form-item label="发生时间" prop="incidentDate" required>
          <el-date-picker
            v-model="editForm.incidentDate"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="伤害描述" prop="injuryDescription">
          <el-input v-model="editForm.injuryDescription" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="处理人" prop="handler">
          <el-input v-model="editForm.handler"></el-input>
        </el-form-item>
        <el-form-item label="处理时间" prop="handledAt">
          <el-date-picker
            v-model="editForm.handledAt"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择处理时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEdit">确定</el-button>
          <el-button @click="editVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog
      v-model="addVisible"
      title="新增坠物事件"
      width="50%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="120px"
      >
        <el-form-item label="事件ID" prop="incidentId" required>
          <el-input v-model="addForm.incidentId"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" required>
          <el-select v-model="addForm.status" placeholder="请选择状态">
            <el-option label="未发生" value="未发生"></el-option>
            <el-option label="已发生" value="已发生"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房产ID" prop="propertyId" required>
          <el-input v-model.number="addForm.propertyId" type="number"></el-input>
        </el-form-item>
        <el-form-item label="居民ID" prop="residentId" required>
          <el-input v-model.number="addForm.residentId" type="number"></el-input>
        </el-form-item>
        <el-form-item label="发生时间" prop="incidentDate" required>
          <el-date-picker
            v-model="addForm.incidentDate"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="伤害描述" prop="injuryDescription">
          <el-input v-model="addForm.injuryDescription" type="textarea"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd">提交</el-button>
          <el-button @click="addVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 数据操作区 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="6">
        <el-input 
          placeholder="居民姓名" 
          v-model="searchResidentName" 
          @keyup.enter="searchEvents"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-select v-model="searchStatus" placeholder="事件状态">
          <el-option label="全部" value=""></el-option>
          <el-option label="未发生" value="未发生"></el-option>
          <el-option label="已发生" value="已发生"></el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-button 
          type="primary" 
          icon="el-icon-search" 
          @click="searchEvents"
        >
          查询
        </el-button>
      </el-col>
      <el-col :span="4">
        <el-button 
          type="success" 
          icon="el-icon-plus" 
          @click="openAddDialog"
        >
          新增事件
        </el-button>
      </el-col>
    </el-row>

    <!-- 事件表格 -->
    <el-table 
      :data="eventData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
      border 
      style="width: 100%;"
      height="450"
      v-loading="loading"
    >
      <el-table-column prop="incidentId" label="事件ID" width="180" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === '已发生' ? 'danger' : 'warning'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="propertyId" label="房产ID" width="100" align="center"></el-table-column>
      <el-table-column prop="residentId" label="居民ID" width="120" align="center"></el-table-column>
      <el-table-column prop="incidentDate" label="发生时间" width="180" align="center" :formatter="formatDateTime"></el-table-column>
      <el-table-column prop="handler" label="处理人" width="120" align="center"></el-table-column>
      <el-table-column prop="handledAt" label="处理时间" width="180" align="center" :formatter="formatDateTime"></el-table-column>
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button type="primary" size="mini" icon="el-icon-view" @click="openDetail(scope.row)">查看</el-button>
            <el-button type="warning" size="mini" icon="el-icon-edit" @click="openEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteEvent(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-row type="flex" justify="center" style="margin-top: 20px;">
      <el-pagination 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]" 
        :page-size="pageSize" 
        :total="eventData.length"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox } from 'element-plus'

// 对话框控制
const detailVisible = ref(false)
const editVisible = ref(false)
const addVisible = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)

// 加载状态
const loading = ref(false)

// 搜索参数
const searchStatus = ref('')
const searchResidentName = ref('')

// 事件数据
const eventData = ref([])

// 详情数据
const detailData = reactive({
  incidentId: '',
  status: '',
  propertyId: null,
  residentId: null,
  incidentDate: null,
  injuryDescription: '',
  handler: '',
  handledAt: null
})

// 编辑表单
const editForm = reactive({
  incidentId: '',
  status: '',
  propertyId: null,
  residentId: null,
  incidentDate: null,
  injuryDescription: '',
  handler: '',
  handledAt: null
})

// 新增表单
const addForm = reactive({
  incidentId: '',
  status: '',
  propertyId: null,
  residentId: null,
  incidentDate: null,
  injuryDescription: '',
  handler: '',
  handledAt: null
})

// 表单验证规则
const rules = reactive({
  incidentId: [
    { required: true, message: '事件ID不能为空', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  propertyId: [
    { required: true, message: '房产ID不能为空', trigger: 'blur' },
    { type: 'number', message: '房产ID必须为数字', trigger: 'blur' }
  ],
  residentId: [
    { required: true, message: '居民ID不能为空', trigger: 'blur' },
    { type: 'number', message: '居民ID必须为数字', trigger: 'blur' }
  ],
  incidentDate: [
    { required: true, message: '请选择发生时间', trigger: 'change' }
  ]
})

// 日期时间格式化
const formatDateTime = (row, column, cellValue) => {
  if (!cellValue) return ''
  const date = new Date(cellValue)
  return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`
}

// 打开详情对话框
function openDetail(row) {
  Object.assign(detailData, row)
  detailVisible.value = true
}

// 打开编辑对话框
function openEdit(row) {
  Object.assign(editForm, row)
  editVisible.value = true
}

// 打开新增对话框
function openAddDialog() {
  addVisible.value = true
}

// 分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}

// 当前页变化
function handleCurrentChange(val) {
  currentPage.value = val
}

// 提交编辑
function submitEdit() {
  loading.value = true
  post('/sc/fallingobject/updateById', editForm, (res) => {
    loading.value = false
    if (res.success) {
      ElMessage.success('更新成功')
      editVisible.value = false
      fetchEvents()
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  }, (error) => {
    loading.value = false
    ElMessage.error(`更新失败: ${error.message}`)
  })
}

// 提交新增
function submitAdd() {
  loading.value = true
  post('/sc/fallingobject/add', addForm, (res) => {
    loading.value = false
    if (res.success) {
      ElMessage.success('添加成功')
      addVisible.value = false
      fetchEvents()
    } else {
      ElMessage.error(res.message || '添加失败')
    }
  }, (error) => {
    loading.value = false
    ElMessage.error(`添加失败: ${error.message}`)
  })
}

// 删除事件
function deleteEvent(row) {
  ElMessageBox.confirm(`确定删除事件 ${row.incidentId} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    post('/sc/fallingobject/deleteById', { incidentId: row.incidentId }, (res) => {
      loading.value = false
      if (res.success) {
        ElMessage.success('删除成功')
        fetchEvents()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }, (error) => {
      loading.value = false
      ElMessage.error(`删除失败: ${error.message}`)
    })
  }).catch(() => {})
}

// 查询事件
// 查询事件 - 确保参数名称与后端一致
function searchEvents() {
  loading.value = true
  console.log('搜索参数:', {
    status: searchStatus.value,
    residentName: searchResidentName.value
  })
  
  post('/sc/fallingobject/byStatusAndName', {
    status: searchStatus.value,
    residentName: searchResidentName.value
  }, (res) => {
    loading.value = false
    console.log('搜索响应:', res)
    
    // 根据图片中的响应格式，res直接是数组而不是{success, data}结构
    if (Array.isArray(res)) {
      eventData.value = res
      if (res.length > 0) {
        ElMessage.success(`找到 ${res.length} 条记录`)
      } else {
        ElMessage.warning('未找到匹配记录')
      }
    } else if (res && Array.isArray(res.data)) {
      // 兼容其他可能的返回格式
      eventData.value = res.data
      if (res.data.length > 0) {
        ElMessage.success(`找到 ${res.data.length} 条记录`)
      } else {
        ElMessage.warning('未找到匹配记录')
      }
    } else {
      eventData.value = []
      ElMessage.warning('未找到匹配记录')
    }
  }, (error) => {
    loading.value = false
    console.error('搜索错误:', error)
    ElMessage.error(`查询失败: ${error.message}`)
  })
}

// 获取所有事件
function fetchEvents() {
  loading.value = true;
  post('/sc/fallingobject/getAll', {}, (res) => {
    loading.value = false;
    console.log('完整响应:', res); // 调试用，查看实际响应结构
    // 适配后端返回结构：如果后端返回 status: 1 表示成功
    if (res.status === 1) {
      eventData.value = res.data || [];
      ElMessage.success('数据加载成功');
    } else {
      // 如果后端使用其他字段，如 code: 200
      ElMessage.error(res.msg || '获取数据失败');
    }
  }, (error) => {
    loading.value = false;
    ElMessage.error(`请求失败: ${error.message}`);
  });
}

onMounted(() => {
  fetchEvents()
})
</script>

<style scoped>
.falling-container {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 8px;
}

.el-table {
  margin-top: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}

.demo-editForm, .add-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 22px;
}
</style>